from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from models import Product, Category, Supplier, Inventory, StockIn, StockOut, db
from utils import error
from datetime import datetime, timedelta, date

statistics_api = Blueprint('statistics_api', __name__, url_prefix='/api/statistics')

@statistics_api.route('/dashboard/', methods=['GET'])
@jwt_required()
def get_dashboard_statistics():
    """获取仪表板统计数据"""
    try:
        # 总商品数
        total_products = Product.query.filter_by(status='active').count()
        
        # 总供应商数
        total_suppliers = Supplier.query.count()
        
        # 总库存价值
        total_stock_value = db.session.query(
            db.func.sum(Inventory.current_stock * Product.cost_price)
        ).join(Product).filter(Product.status == 'active').scalar() or 0
        
        # 低库存商品数
        low_stock_count = db.session.query(Inventory).join(Product).filter(
            Inventory.current_stock <= Product.min_stock,
            Product.status == 'active'
        ).count()
        
        # 今日入库数量
        today = date.today()
        today_stock_in = StockIn.query.filter(
            db.func.date(StockIn.created_at) == today,
            StockIn.status == 'completed'
        ).with_entities(db.func.sum(StockIn.quantity)).scalar() or 0
        
        # 今日出库数量
        today_stock_out = StockOut.query.filter(
            db.func.date(StockOut.created_at) == today,
            StockOut.status == 'completed'
        ).with_entities(db.func.sum(StockOut.quantity)).scalar() or 0
        
        # 今日入库金额
        today_stock_in_amount = StockIn.query.filter(
            db.func.date(StockIn.created_at) == today,
            StockIn.status == 'completed'
        ).with_entities(db.func.sum(StockIn.total_amount)).scalar() or 0
        
        # 今日出库金额
        today_stock_out_amount = StockOut.query.filter(
            db.func.date(StockOut.created_at) == today,
            StockOut.status == 'completed'
        ).with_entities(db.func.sum(StockOut.total_amount)).scalar() or 0
        
        return jsonify({
            'success': True,
            'data': {
                'total_products': total_products,
                'total_suppliers': total_suppliers,
                'total_stock_value': float(total_stock_value),
                'low_stock_count': low_stock_count,
                'today_stock_in': int(today_stock_in),
                'today_stock_out': int(today_stock_out),
                'today_stock_in_amount': float(today_stock_in_amount),
                'today_stock_out_amount': float(today_stock_out_amount)
            }
        })
        
    except Exception as e:
        return error(500, f'Failed to get dashboard statistics: {str(e)}').to_response()
